import type { RouteRecordRaw } from 'vue-router';

import { nextTick } from 'vue';
import { createRouter, createWebHashHistory } from 'vue-router';

export const isLoaded: { value: boolean } = { value: false };

const routerHistory = createWebHashHistory(import.meta.env.BASE_URL);
// const removeRoutes: Array<() => void> = [];
// const WHITE_LIST = new Set([
//   '/login',
// ]);

export function setupRouter(routes: RouteRecordRaw[]) {
  const router = createRouter({
    history: routerHistory,
    strict: true,
    sensitive: true,
    routes,
    scrollBehavior(to, from, savedPosition) {
      const isChange = to.hash && to.hash !== from.hash;
      return isChange
        ? { el: to.hash, behavior: 'smooth' }
        : savedPosition || { top: 0 };
    },
  });

  // 移除末尾 `/`
  // router.beforeEach((to, _, next) => {
  //   if (/.\/$/.test(to.path)) {
  //     to.meta.redirectCode = 301;
  //     next({ path: to.path.replace(/\/$/, ''), replace: true });
  //   } else {
  //     next({ ...to, replace: true });
  //   }
  // });

  router.beforeEach(async (to, from, next) => {
    next();
    // if ((!from || to.path !== from.path)) {
    // }

    // const userStore = useUserStore();

    // if (userStore.token) {
    //   if (to.path === '/login') {
    //     next({ path: '/', replace: true });
    //   } else {
    //     const dynamicRoutes: RouteRecordRaw[] = [];

    //     if (!isLoaded.value && Array.isArray(dynamicRoutes)) {
    //       removeRoutes.forEach(r => r());
    //       removeRoutes.length = 0;

    //       if (dynamicRoutes.length > 0) {
    //         dynamicRoutes.forEach((r) => {
    //           removeRoutes.push(router.addRoute('Home', r));
    //         });
    //       }

    //       isLoaded.value = true;
    //     }

    //     next();
    //   }
    // } else {
    //   if (WHITE_LIST.has(to.path)) {
    //     next();
    //   } else {
    //     let query = to.query;
    //     if (to.path !== '/') {
    //       const redirect = { redirect: to.path };
    //       query = query ? Object.assign(query, redirect) : redirect;
    //     }
    //     next({ path: '/login', query, hash: to.hash, replace: true });
    //   }
    // }
  });

  router.afterEach((to, from) => {
    if ((!from || to.path !== from.path) && to.hash && to.hash !== from.hash) {
      nextTick(() => {
        const el = document.querySelector(to.hash);
        if (el) {
          el.scrollIntoView();
        }
      });
    }
  });

  return router;
}

if (import.meta.env.DEV) {
  const dirLog = {
    '': '？',
    'back': '⏪',
    'forward': '⏩',
  };
  routerHistory.listen((to, from, message) => {
    // eslint-disable-next-line no-console
    console.log(`${dirLog[message.direction]} as a ${message.type}`);
  });
}
